/**
 * 
 */
package com.hoopchina.ui.main;

import com.hoopchina.news.R;
import com.hoopchina.meta.WeatherInfo;
import com.hoopchina.service.Networking;
import com.hoopchina.settings.CitySettingDialog;
import com.hoopchina.ui.home.CityEngine;
import com.hoopchina.ui.home.GetLocation;
import com.hoopchina.ui.home.HomeView;
import com.hoopchina.util.xml.WeatherInfoXML;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

/**
 * WeatherBox
 * 天气显示控件
 * 
 * @author Neusoft
 */
public class WeatherBox extends LinearLayout {
	protected static final int	 WEATHER_GET_OK	      = 0;
	protected static final int	 LOCATION_GET_OK	  = 1;
	public static final String	 PREFS_NAME	          = "MyPrefsFile";
	public final String	         HTTP_WEATHER_SERVER  = "http://newsmobile.baidu.com/n?m=app&v=weather&loc=";
	// public final String HTTP_DEFAULT_CITY = "北京";
	private Context	             mContext	          = null;
	private RelativeLayout	     mWeatherBox	      = null;
	private ImageView	         mImageViewWeather	  = null;
	private TextView	         mTextViewTemperature = null;
	private TextView	         mTextViewCity	      = null;
	private TextView	         mTextViewWeather	  = null;
	private String	             mCurrentProvince	  = null;
	private String	             mCurrentCity	      = null;
	private String	             mCurrentCityCode	  = null;
	private CityEngine	         mCityEngine	      = null;
	private String[]	         mProvinceNames	      = null;
	private int[]	             mProvinceCodes	      = null;
	// private static final String[]
	private ArrayAdapter<String> mAdapterProvince	  = null;
	private ArrayAdapter<String> mAdapterCity	  	  = null;
	private String[]	         mCities	          = null;
	private SharedPreferences	 mSettings	          = null;
	public  static final  int    Weather_Selected=1;
	public  static final  int    News_Place_Selected=2;

   /**
     * 返回天气信息
     */
    public String getWeather() {
        return (String)this.mImageViewWeather.getTag();
    }
    
    

	/*
	 * 根据城市编码获取该城市天气
	 */
	public WeatherInfo getWeatherFromServer(String cityCode) {
		WeatherInfo weather = null;

		String url = HTTP_WEATHER_SERVER + cityCode;
		try {
	        weather = (new WeatherInfoXML()).getWeatherInfo(Networking.getStreamFromUrl(url)); 
		} catch (Exception e) {
			weather = null;
			e.printStackTrace();
		}

		return weather;
	}

    /**
     * 获取温度信息
     */
    public String getTemperature() {
        return mTextViewTemperature.getText().toString();
    }

    /**
     * 设置温度信息
     */
    public void setTemperature( String temperature ) {
        this.mTextViewTemperature.setText( temperature );
    }

    /**
     * 返回当前城市
     */
    public String getCity() {
        return mTextViewCity.getText().toString();
    }

    /**
     * 设置当前城市
     */
    public void setCity( String city ) {
        this.mTextViewCity.setText( city );
    }

    /**
     * 构造器
     */
    public WeatherBox( Context context ) {
        super( context );
        init(context);
    }

    /**
     * 构造器
     */
    public WeatherBox( Context context, AttributeSet attrs ) {
        super( context, attrs );
        init(context);
        
    }
    /*
     * 处理异步返回数据
     */
    private Handler mHandler = new Handler(){
    	public void handleMessage(android.os.Message msg){
    		WeatherInfo weatherInfo = (WeatherInfo)msg.obj;
              switch(msg.what){
              case WEATHER_GET_OK:
            	  refreshWeatherView(weatherInfo);
                  break;

              case LOCATION_GET_OK:
                  Bundle data = new Bundle();
                  data = msg.getData();
                  mCurrentCity = data.getString( "city" );
                  mCurrentProvince = data.getString( "province" );
                  setLocationPreference();
                  setLocationPreferenceNews();
                  refresh();
                  break;
              default:
                  break;
              }
    	}
    };
    /*
     * 加载本地省市信息(天气)
     */
    private void getLocationPreferenceForWeather( ) {
        if ( null == mSettings)
            return;

        mCurrentProvince = mSettings.getString( "mCurrentProvince", CitySettingDialog.HTTP_DEFAULT_CITY );
        mCurrentCity = mSettings.getString( "mCurrentCity", CitySettingDialog.HTTP_DEFAULT_CITY );
    }
    
    /*
     * 加载本地省市信息（新闻）
     */
    private void getLocationPreferenceForNews( ) {
        if ( null == mSettings)
            return; 
        mCurrentProvince = mSettings.getString( "mCurrentProvinceNews", CitySettingDialog.HTTP_DEFAULT_CITY );
        mCurrentCity = mSettings.getString( "mCurrentCityNews", CitySettingDialog.HTTP_DEFAULT_CITY );
    }
    /*
     * 写入本地省市信息
     */
    private void setLocationPreference() {
        if ( null == mSettings )
            return;

        SharedPreferences.Editor editor = mSettings.edit();
        editor.putString( "mCurrentProvince", mCurrentProvince );
        editor.putString( "mCurrentCity", mCurrentCity );
        editor.commit();
    }
    /*
     * 写入城市信息，该城市新闻
     */
    private void setLocationPreferenceNews() {
        if ( null == mSettings )
            return;
        SharedPreferences.Editor editor = mSettings.edit();
        editor.putString("mCurrentProvinceNews", mCurrentProvince);
        editor.putString("mCurrentCityNews", mCurrentCity);
        editor.commit();
    }
    /*
     * 刷新天气框
     */
    public synchronized void refreshWeatherView(WeatherInfo weatherInfo) {
		mTextViewTemperature.setText(weatherInfo.getTemperature());
		setWeather(weatherInfo.getWeatherType()); 
    }
    /*
     * 重新获取当前天气
     */
	public void refreshWeather() {
		new Thread() {
			WeatherInfo weatherInfo = null;
			
            @Override
            public void run() {
            	weatherInfo = getWeatherFromServer(mCurrentCityCode);
            	if (null != weatherInfo) {
    				Message msg = mHandler.obtainMessage();
    				msg.what = WEATHER_GET_OK;
    				msg.obj = weatherInfo;
    				mHandler.sendMessage(msg);
        		}
            }
			
		}.start();
	}
	/*
	 * 根据当前城市获得城市id，并调用刷新天气方法
	 */
    void refresh() {
        if(null == mSettings)
            return;
		mCurrentProvince = mSettings.getString("mCurrentProvince", CitySettingDialog.HTTP_DEFAULT_CITY);  
		mCurrentCity = mSettings.getString("mCurrentCity", CitySettingDialog.HTTP_DEFAULT_CITY);
		setCity(mCurrentCity);
		mCurrentCityCode = mCityEngine.getCityCode(mCurrentCity);
		refreshWeather();
    }

	/*
	 * 初始化资源
	 */
	void init(Context context) {
		mContext = context;
		mSettings = mContext.getSharedPreferences(PREFS_NAME, 0); 
		//保存默认省市
		//setLocationPreference();
		//setLocationPreferenceNews();
		//获得省的名字和编码
		mProvinceNames = mContext.getResources().getStringArray(R.array.a_settings_province_names);
		mProvinceCodes = mContext.getResources().getIntArray(R.array.a_settings_province_codes);
		mCityEngine = new CityEngine(mContext);
		Log.d("GetLocation","init()");
		GetLocation locationGetter = new GetLocation( mContext );
		//根据网络，获得省市信息
		locationGetter.getLocation( LOCATION_GET_OK, mHandler );
		
		String infServiString = Context.LAYOUT_INFLATER_SERVICE;
		LayoutInflater lInflater;
		lInflater = (LayoutInflater) getContext().getSystemService(
				infServiString);
		lInflater.inflate(R.layout.titlebarweatherbox, this, true);
		mImageViewWeather = (ImageView) findViewById(R.id.imageViewWeather);
		mTextViewTemperature = (TextView) findViewById(R.id.textViewTemperature);

		mTextViewCity = (TextView) findViewById(R.id.textViewCity);

		mTextViewWeather = (TextView) findViewById(R.id.textViewWeather);
		mWeatherBox = (RelativeLayout) findViewById(R.id.relativeLayoutWeather);
		mWeatherBox.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				citySelect(Weather_Selected,null);
			}
		});
		
		refresh();
	}
	
	/*
	 * 获得gps定位信息
	 */
    private void AsyncGetLocation() {
        new Thread(){
            public void run(){
                GetLocation locationGetter = new GetLocation( mContext );
//                locationGetter.start( new GetLocation.Callback() {
//                    
//                    @Override
//                    public void onGetComplete(String aCurProvince, String aCurCity) {
//                        Message msg = mHandler.obtainMessage();
//                        Bundle data = new Bundle();
//                        data.putString( "city", aCurCity );
//                        data.putString( "province", aCurProvince );
//                        msg.setData( data );
//                        msg.what = LOCATION_GET_OK;
//                        mHandler.sendMessage( msg );
//                        
//                    }
//                });
                locationGetter.getLocation( LOCATION_GET_OK, mHandler );
            }
        }.start();
    }
    
    /**
     * 城市选择对话框
     */
    public void citySelect(final int resultNum,final ILocalNewsChanged localNewsChanged) {
		LayoutInflater inflater = LayoutInflater.from(mContext);
		mAdapterProvince = new ArrayAdapter<String>(mContext,
				android.R.layout.simple_spinner_item, mProvinceNames);

		View layout = inflater.inflate(R.layout.dialogarea,
				(ViewGroup) findViewById(R.id.dialogarea));
		final Spinner spinnerCity = (Spinner) layout
				.findViewById(R.id.spinnerCity);
		spinnerCity.setEnabled(false);

		Spinner spinnerProvince = (Spinner) layout
				.findViewById(R.id.spinnerProvince);
		// 设置下拉列表的风格
		mAdapterProvince.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 将adapter 添加到m_Spinner中
		if (resultNum==Weather_Selected) {
			getLocationPreferenceForWeather();
		}else {
			getLocationPreferenceForNews();
		}
		
		spinnerProvince.setAdapter(mAdapterProvince);
		int position = 0;
		for ( ; position<mProvinceNames.length ; position++) {
			if ( mCurrentProvince.equals(mProvinceNames[position]) ) {
				break;
			}
		}
		if (position >= mProvinceCodes.length) {
			return;
		}
		spinnerProvince.setSelection(position, true);
		//返回某省下的城市列表
		mCities = mCityEngine.getCitys(mProvinceCodes[position] , mProvinceCodes[position+1]);
		if ( 0 == mCities.length ){
			mCities = new String[]{mCurrentProvince};
		}
		mAdapterCity = new ArrayAdapter<String>(
				mContext,
				android.R.layout.simple_spinner_item,
				mCities);
		// 设置下拉列表的风格
		mAdapterCity.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 将adapter 添加到m_Spinner中
		spinnerCity.setAdapter(mAdapterCity);
		// set
		spinnerCity.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0,
					View arg1, int arg2, long arg3) {
				mCurrentCity = mCities[arg2];
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		
		
		int positionCity = 0;
		for (; positionCity < mCities.length ; positionCity++) {
			if ( mCurrentCity.equals(mCities[positionCity]) ) {
				break;
			}
		}
		if (positionCity==mCities.length) {
			positionCity=mCities.length-1;
		}
		spinnerCity.setSelection(positionCity, true);

		spinnerCity.setEnabled(true);

		
		
		spinnerProvince.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0,
					View arg1, int arg2, long arg3) {
				mCurrentProvince = mProvinceNames[arg2];
//				Toast.makeText(mContext,
//						arg2 + ":" + mProvinceNames[arg2], 2000).show();
				mCities = mCityEngine.getCitys(mProvinceCodes[arg2] , mProvinceCodes[arg2+1]);
				if ( 0 == mCities.length ){
					mCities = new String[]{mCurrentProvince};
				}
				mAdapterCity = new ArrayAdapter<String>(
						mContext,
						android.R.layout.simple_spinner_item,
						mCities);
				// 设置下拉列表的风格
				mAdapterCity.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				// 将adapter 添加到m_Spinner中
				spinnerCity.setAdapter(mAdapterCity);

				spinnerCity.setEnabled(true);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
		new AlertDialog.Builder(mContext).setTitle(R.string.app_settings_dialog_title_city)
				.setView(layout).setPositiveButton("确定", new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						if (resultNum==Weather_Selected) {
							setLocationPreference();
							refresh();
						}else {
							 String mOldCity = mSettings.getString("mCurrentCityNews", CitySettingDialog.HTTP_DEFAULT_CITY);
							 if (!mOldCity.equals(mCurrentCity)) {
								    setLocationPreferenceNews();
									localNewsChanged.refreshLocalNewsList();
								}
							
						}
					    

					}} ).setNegativeButton("取消", null).show();
	}
    
    
    /**
     * 显示天气图片和文字
     */
    public void setWeather( String weather ) {
        mImageViewWeather.setTag( weather );
        Log.d("sui",weather);
        mTextViewWeather.setText(weather);
        if(weather.contains("转")) {
        	weather = weather.substring(weather.lastIndexOf("转")+1);
        	Log.d("sui",weather);
        }
        if(weather.equals( "晴" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_clear );
        } 
        else if (weather.equals( "多云" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_cloudy );
        }
        else if (weather.equals( "沙尘" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_dust );
        }
        else if (weather.equals( "雾" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_fog );
        }
        else if (weather.equals( "冻雨" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_freezing_rain );
        }
        else if (weather.equals( "冰雹" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_hail );
        }
        else if (weather.equals( "大雨" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_heavy_rain );
        }
        else if (weather.equals( "小雨" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_light_rain );
        }
        else if (weather.equals( "小雪" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_light_snow );
        }
        else if (weather.equals( "阵雨" )) {
        	mTextViewWeather.setText("阵雨");
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_shower );
        }
        else if (weather.equals( "雨夹雪" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_sleet );
        }
        else if (weather.equals( "雪" )) {
        	mTextViewWeather.setText("雪");
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_snow );
        }
        else if (weather.equals( "雷阵雨" )) {
            this.mImageViewWeather.setBackgroundResource( R.drawable.image_weather_thunder_shower );
        } else{
        	//TODO: change to default image
        	this.mImageViewWeather.setBackgroundResource(R.drawable.image_weather_cloudy );
        }

    }

}
